#include "WriteLog.h"
#include "macro.h"
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <QTimer>

WriteLog::WriteLog()
{
    fileToWriteLog=new QFile(this);

    QDir dir(LogFileDir);
    if(!dir.exists())
        dir.mkdir(LogFileDir); //如果不存在存放日志的文件夹，则创建文件夹

    fileToWriteLog->setFileName(LogFileDir+QDate::currentDate().toString()+".txt");
    if (!fileToWriteLog->open(QIODevice::WriteOnly | QIODevice::Text|QIODevice::Append))
        qDebug()<<"ERROR to open log file";

    QTimer::singleShot(QTime::currentTime().msecsTo(QTime(23,59,59,999))+1000,this,SLOT(slotCreateNewLogFile()));
}

void WriteLog::slotWriteLog(QByteArray log)
{
    if(fileToWriteLog->isOpen())
    {
        fileToWriteLog->write(QDateTime::currentDateTime().toString().toUtf8()
              +'\t'+log+'\n');
        fileToWriteLog->flush();
    }
}

void WriteLog::slotCreateNewLogFile()
{
    qint64 miliSecs=QTime::currentTime().msecsTo(QTime(23,59,59,999));
    if(miliSecs>60000) // 确保在24点后而不是24点前
    {
        fileToWriteLog->flush();
        fileToWriteLog->close();
        fileToWriteLog->setFileName(LogFileDir+QDate::currentDate().toString()+".txt");
        if (!fileToWriteLog->open(QIODevice::WriteOnly | QIODevice::Text|QIODevice::Append))
            qDebug()<<"ERROR to open log file";

    }
    QTimer::singleShot(miliSecs+1000,this,SLOT(slotCreateNewLogFile()));
}

WriteLog::~WriteLog()
{

}

